import 'package:enterprise_v6_app/app/components/dialog/exit_tips.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/user_manager.dart';
import 'package:enterprise_v6_app/app/data/entities/application/department_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/role_personnel_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/job_plan_details_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_plan_request/job_plan_request_controller.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/special_list_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class PlanningRequestController extends GetxController {
  ///外部列表controller
  final specialListController = Get.find<SpecialListController>();

  /// 作业计划controller
  final jobPlanRequestController = Get.find<JobPlanRequestController>();

  /// 计划申请详情实体
  JobPlanDetailsEntity jobPlanDetailsEntity = JobPlanDetailsEntity();

  // 作业编号输入控制器
  final jobNumberController = TextEditingController();

  // 作业名称输入控制器
  final jobNameController = TextEditingController();

  // 作业内容输入控制器
  final jobContentController = TextEditingController();

  // 作业地点选取
  void jobLocationSelect() {
    Get.toNamed(AppRoutes.planSelectedLocation)?.then((value) {
      if (value != null && value is Map) {
        final Map<String, double> laAndLon = value['laAndLon'] as Map<String, double>;
        final String ticketAddress = value['ticketAddress'] as String;
        jobPlanDetailsEntity.longitude = laAndLon['longitude'];
        jobPlanDetailsEntity.latitude = laAndLon['latitude'];
        jobPlanDetailsEntity.ticketAddress = ticketAddress;
        update();
      }
    });
  }

  // 选择风险辨识人
  void riskIdentificationPersonSelect() {
    Get.toNamed(AppRoutes.personnelSelection, arguments: {
      'queryParameters': {'roleName': '风险辨识人'},
      'isRadio': true,
    })?.then((value) {
      //如果不为空则设置人员信息
      if (value != null && value is List<RolePersonnelEntity>) {
        final RolePersonnelEntity riskIdentificationPerson = value.first;
        jobPlanDetailsEntity.identityUserId = riskIdentificationPerson.getId();
        jobPlanDetailsEntity.identityUserName = riskIdentificationPerson.getShowName();
        update();
      }
    });
  }

  // 申请单位选取
  void applyUnitSelect() {
    Get.toNamed(AppRoutes.unitSelection, arguments: {
      'queryParameters': {'type': 2},
      'isRadio': true,
    })?.then((value) {
      //如果不为空则设置单位信息
      if (value != null) {
        value as List<DepartmentEntity>;
        jobPlanDetailsEntity.applyDepartmentName = value[0].getShowName();
        jobPlanDetailsEntity.applyDepartmentId = value[0].getId();
      }
      update();
    });
  }

  // 删除计划
  void deletePlan() {
    Get.dialog<bool>(ExitTips(
      content: '确认撤销此作业计划?',
      func: (v) async {
        if (v) {
          final res = await HttpUtil().generateDeleteRequest(
            Interface.jobDelete,
            queryParameters: {
              'id': jobPlanDetailsEntity.id,
            },
          ).execute();
          res.onSuccess((result) {
            Get.back();
            specialListController.refreshPage();
            AppToast.showSuccess('撤销成功!');
          });
        }
      },
    ));
  }

  // 作业计划申请提交 审批完成之前可修改，修改后提示下方文字
  void submit() async {
    jobPlanDetailsEntity.applyUserId = UserManager.getUserId();
    jobPlanDetailsEntity.applyUserName = UserManager.getUser()?.systemUser?.nickname;
    jobPlanDetailsEntity.ticketContent = jobContentController.text;
    jobPlanDetailsEntity.ticketName = jobNameController.text;
    jobPlanDetailsEntity.ticketNo = jobNumberController.text;
    // final data = {
    // 'applyDepartmentId': applyUnitId, // 申请单位ID String
    // 'applyDepartmentName': applyUnit, // 申请单位名称 String
    // 'applyUserId': UserManager.getUserId(), // 申请人用户ID String
    // 'applyUserName':
    //     UserManager.getUser()?.systemUser?.nickname, // 申请人用户姓名 String
    // 'createBy': '', // 创建人 String
    // 'createDate': '', // 创建时间 String(date-time)
    // 'departmentId': '', // 属地单位ID String
    // 'id': '', // 主键ID String
    // 'identityUserId': riskIdentificationPerson.userId, // 风险辨识人ID String
    // 'identityUserName': riskIdentificationPerson.userName, // 风险辨识人姓名 String
    // 'latitude': latitude, // 纬度 Object
    // 'longitude': longitude, // 经度 Object
    // 'planEndDate': planJobTimeEnd, // 作业计划结束时间 String(date-time)
    // 'planStartDate': planJobTimeStart, // 作业计划开始时间 String(date-time)
    // 'ticketAddress': ticketAddress, // 作业地点 String
    // 'companyCode': companyCode, // 企业code String
    // 'ticketContent': jobContentController.text, // 作业内容 String
    // 'ticketName': jobNameController.text, // 作业名称 String
    // 'ticketNo': jobNumberController.text, // 作业编号 String
    // 'ticketSource': '', // 作业来源 String
    // 'updateBy': '', // 修改人 String
    // 'updateDate': '' // 修改时间 String(date-time)
    // };
    if (submitJob()) {
      if (jobPlanDetailsEntity.id!.isNotEmpty) {
        final res = await HttpUtil()
            .generatePostRequest(
              Interface.jobPlanUpdateUrl,
              data: jobPlanDetailsEntity.toJson(),
            )
            .execute();
        res.onSuccess((result) {
          // Get.dialog<bool>(
          //   ExitTips(
          //     content: '作业计划调整，请确认是否需要重新辨识',
          //     func: (v) {
          //       if (v) {
          //         Get.back();
          //         specialListController.refreshPage();
          //         AppToast.showSuccess('提交成功');
          //       }
          //     },
          //   ),
          // );
          Get.back();
          specialListController.refreshPage();
          AppToast.showSuccess('修改成功');
        });
      } else {
        final res = await HttpUtil()
            .generatePostRequest(
              Interface.jobApplyUrl,
              data: jobPlanDetailsEntity.toJson(),
            )
            .execute();
        res.onSuccess((result) {
          Get.back();
          specialListController.refreshPage();
          AppToast.showSuccess('提交成功');
        });
      }
    }
  }

  // 提交时判断
  bool submitJob() {
    // if (jobNumberController.text.isEmpty) {
    //   AppToast.showWarning('请输入作业编号');
    //   return false;
    // }
    if (jobNameController.text.isEmpty) {
      AppToast.showWarning('请输入作业名称');
      return false;
    }
    if (jobContentController.text.isEmpty) {
      AppToast.showWarning('请输入作业内容');
      return false;
    }
    if (jobPlanDetailsEntity.planStartDate!.isEmpty) {
      AppToast.showWarning('请选择计划作业开始时间');
      return false;
    }
    if (jobPlanDetailsEntity.planEndDate!.isEmpty) {
      AppToast.showWarning('请选择计划作业结束时间');
      return false;
    }
    if (jobPlanDetailsEntity.applyDepartmentName!.isEmpty) {
      AppToast.showWarning('请选择申请单位');
      return false;
    }
    if (jobPlanDetailsEntity.ticketAddress!.isEmpty) {
      AppToast.showWarning('请输入作业地点');
      return false;
    }
    if (jobPlanDetailsEntity.identityUserId!.isEmpty) {
      AppToast.showWarning('请选择风险辨识人');
      return false;
    }
    return true;
  }

  /// 获取计划申请详情
  void _initPlanDetail() async {
    jobNumberController.text = jobPlanDetailsEntity.ticketNo!;
    jobNameController.text = jobPlanDetailsEntity.ticketName!;
    jobContentController.text = jobPlanDetailsEntity.ticketContent!;
    update();
  }

  @override
  void onReady() {
    super.onReady();
    if (Get.arguments != null && Get.arguments is String) {
      jobPlanDetailsEntity = jobPlanRequestController.jobPlanDetailsEntity;
      _initPlanDetail();
    }
  }

  @override
  void onClose() {
    jobNumberController.dispose();
    jobNameController.dispose();
    jobContentController.dispose();
    super.onClose();
  }
}
